<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.name" placeholder="请输入组名称" @keyup.enter.native="$refs.table.refresh(true)" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="setEmpty">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div v-if="!$store.getters.isMzRole" class="table-operator">
      <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button icon="delete" @click="handleDeleteBatch">删除</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="leader" slot-scope="text, record">
        <template>
          <span
            v-for="tag in record.members"
            :key="tag.userId"
          >
            <a-tag
              v-if="tag.leaderFlag === 1"
              color="green"
            >
              {{ tag.nickName }}
            </a-tag>
          </span>
        </template>
      </span>
      <span slot="team" slot-scope="text, record">
        <template>
          <span
            v-for="tag in record.members"
            :key="tag.userId"
          >
            <a-tag
              v-if="tag.leaderFlag === 0"
              color="green"
            >
              {{ tag.nickName }}
            </a-tag>
          </span>
        </template>
      </span>
      <span slot="declarationInfos" slot-scope="text">
        <a-tag
          v-for="tag in text"
          :key="tag.id"
          color="blue"
        >
          {{ tag.userName }}
        </a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleCheck(record)">查看</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
          <a-divider type="vertical" />
          <a @click="handleAllpcationEdit(record)">分配申报组织</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <check-form
      ref="checkModal"
    />
    <allocation-form
      ref="allpcationModal"
      :visible="allpcation_visible"
      :loading="allpcation_confirmLoading"
      :model="allpcation_mdl"
      :orgList="orgList"
      :systemDetail="systemDetail"
      @cancel="handleAllpcationCancel"
      @ok="handleAllpcationOk"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getExpert, saveExpert, deleteExpert, addDeclarationInfo, getCurrentDeclarationSystem3 } from '@/api/expert'
import { getOrgList } from '@/api/system'

import CreateForm from './CreateForm'
import CheckForm from './CheckForm'
import AllocationForm from './AllocationForm'

let columns = [
  {
    title: '序号',
    width: '80px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '组名称',
    width: '120px',
    dataIndex: 'name'
  },
  {
    title: '组长',
    width: '100px',
    dataIndex: 'leader',
    scopedSlots: { customRender: 'leader' }
  },
  {
    title: '组员',
    dataIndex: 'team',
    scopedSlots: { customRender: 'team' }
  },
  {
    title: '申报组织',
    dataIndex: 'declarationInfos',
    scopedSlots: { customRender: 'declarationInfos' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Expert',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    CheckForm,
    AllocationForm
  },
  data () {
    // 民政角色不展示操作项
    if (this.$store.getters.isMzRole) {
      columns = columns.filter(v => v.dataIndex != 'action')
    }
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // allpcation model
      allpcation_visible: false,
      allpcation_confirmLoading: false,
      allpcation_mdl: null,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getExpert(requestParameters)
          .then(res => {
            console.log(res)
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      orgList: [],
      systemDetail: {}
    }
  },
  filters: {
  },
  created () {
    this.getCurrentDeclarationSystem3()
    this.getList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    setEmpty () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    getList () {
      getOrgList({
        current: 1,
        size: 10000,
        currentDeclarationSystem: 1
      })
          .then(res => {
            this.orgList = res.resultPage.records
          })
    },
    getCurrentDeclarationSystem3 () {
      getCurrentDeclarationSystem3()
          .then(res => {
            this.systemDetail = res
          })
    },
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        deleteExpert({
            id: this.selectedRowKeys.join(',')
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('批量删除成功')
            })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      let leader = ''
      const team = []
      record.members.forEach(item => {
        if (item.leaderFlag === 1) {
          leader = item.userId
        } else {
          team.push(item.userId)
        }
      })
      this.mdl = { ...record, leader, team }
      this.visible = true
    },
    handleCheck (record) {
      this.$refs.checkModal.checkView(record)
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteExpert({
            id: record.id
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('删除成功')
            })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.team.indexOf(values.leader) > -1) {
            this.$message.warning('组长不能出现在组员中')
            this.confirmLoading = false
            return
          }
          const members = [{
            userId: values.leader,
            leaderFlag: 1
          }]
          values.team.forEach(item => {
            members.push({
              userId: item,
              leaderFlag: 0
            })
          })
          values.members = members
          delete values.leader
          delete values.team
          saveExpert(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleAllpcationEdit (record) {
      const declarationInfoIds = []
      const declarationInfoOldIds = []
      record.declarationInfos.forEach(item => {
        if (item.declarationSystemId === this.systemDetail.id) {
          declarationInfoIds.push(item.id)
        } else {
          declarationInfoOldIds.push(item.id)
        }
      })
      this.allpcation_mdl = { ...record, expertGroupId: record.id, declarationInfoIds, declarationInfoOldIds }
      this.$refs.allpcationModal.targetIds = record.targetRecordIds || []
      this.$refs.allpcationModal.initTypeList()
      this.allpcation_visible = true
    },
    handleAllpcationCancel () {
      this.allpcation_visible = false

      const form = this.$refs.allpcationModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleAllpcationOk () {
      const form = this.$refs.allpcationModal.form
      this.allpcation_confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          values.userIds = this.allpcation_mdl.members.map(item => item.userId)
          values.declarationInfoIds = [...this.allpcation_mdl.declarationInfoOldIds, ...values.declarationInfoIds]
          values.targetIds = this.$refs.allpcationModal.targetIds || []
          console.log('values', values)
          addDeclarationInfo(values).then(res => {
              this.allpcation_visible = false
              this.allpcation_confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('申报组织分配成功')
            }).finally(() => {
              this.allpcation_confirmLoading = false
            })
        } else {
          this.allpcation_confirmLoading = false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
